<template>
  <div class="faultHandlingMode zy-content">
    <div class="searchBox search-box-layout">
      <Row :gutter="24">
        <Col span="4">
          <div>
            <p class="label">{{ $t("工号/姓名") }}</p>
            <div class="ipt">
              <!--              <Select-->
              <!--                  v-model="searchParams.empno"-->
              <!--                  filterable-->
              <!--                  clearable-->
              <!--                  :placeholder="`${$t('common.inputInfo')}`"-->
              <!--                  @on-query-change="timeOutgetUserNo"-->
              <!--              >-->
              <!--                <Option-->
              <!--                    v-for="(item, index) of userNoArr"-->
              <!--                    :value="item.empno"-->
              <!--                    :key="index"-->
              <!--                    :label="item.empno + '-' + item.realname"-->
              <!--                ></Option>-->
              <!--              </Select>-->
              <Input maxlength="200" placeholder="请输入" clearable v-model="searchParams.empNoOrName"/>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t("部门") }}</p>
            <div class="ipt">
              <Select
                  filterable
                  v-model="searchParams.deptId"
                  clearable
                  :placeholder="`${$t('common.selectInfo')}`"
              >
                <Option
                    v-for="item of departmentList"
                    :value="item.id"
                    :label="item.deptName"
                    :key="item.id"
                />
              </Select>
            </div>
          </div>
        </Col>

        <Col span="4">
          <div>
            <p class="label">{{ $t("用户状态") }}</p>
            <div class="ipt">
              <Select v-model="searchParams.status" filterable placeholder>
                <Option
                    v-for="(item, index) of statusArr"
                    :value="item.id"
                    :key="index"
                    :label="item.name"
                ></Option>
              </Select>
            </div>
          </div>
        </Col>
        <!-- <Col span="4">
          <div>
            <p class="label">{{ $t("是否有证书") }}</p>
            <div class="ipt">
              <RadioGroup v-model="searchParams.certificate">
                <Radio :label="-1">{{ $t("全部") }}</Radio>
                <Radio :label="1">{{ $t("common.Yes") }}</Radio>
                <Radio :label="0">{{ $t("common.No") }}</Radio>
              </RadioGroup>
            </div>
          </div>
        </Col>-->
        <Col span="4">
          <div>
            <div class="ipt">
              <p class="label hide-label">--</p>
              <Button
                  class="search-btn"
                  type="primary"
                  v-if="checkBtnPermission.userFindUserList"
                  @click="changeNum()"
              >{{ $t("common.Query") }}
              </Button>
              <Button
                  class="reset-btn"
                  @click="reset()"
                  v-if="checkBtnPermission.userFindUserList"
              >{{ $t("common.reset") }}
              </Button>
            </div>
          </div>
        </Col>
      </Row>
    </div>

    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t("common.listInformation") }}</span>

        <Button
            v-if="checkBtnPermission.userInsert"
            @click="createfaultCodeShowH"
        >{{ $t("common.New") }}
        </Button>
        <Button @click="importExcelShow" v-if="checkBtnPermission.userImport">
          {{
            $t("common.Import")
          }}
        </Button>
        <Button @click="exportTemplate" v-if="checkBtnPermission.userTemplate">
          {{
            $t("preliminary.DownloadTemplate")
          }}
        </Button>
        <Button v-if="checkBtnPermission.userDelete" @click="delFaultCodeShowClick">
          {{
            $t("common.batchDelete")
          }}
        </Button>
        <Button v-if="checkBtnPermission.userUpdate" @click="batchChangeStatus(1)">
          {{ $t("批量启用") }}
        </Button>
        <Button v-if="checkBtnPermission.userUpdate" @click="batchChangeStatus(0)">
          {{ $t("批量禁用") }}
        </Button>
        <Button
            @click="getTableColumns(columns)"
        >{{ handleContextMenuStatus ? $t("显示操作栏") : $t("隐藏操作栏") }}
        </Button>
      </div>
      <div class="tableContent">
        <Table
            :ellipsis="true"
            ref="selection"
            class="resizable-table"
            border
            @on-column-width-resize="onColumnWidthResize"
            :columns="columnsList"
            :data="dataArr"
            @on-selection-change="onSelectChange"
        >
          <template slot-scope="{ row }" slot="action">
            <span
                class="operationBtn"
                @click="createfaultCodeShowH(row)"
                v-if="checkBtnPermission.userUpdate"
            >
              <i class="iconfont zy-common-bianji"></i>
              {{ $t("common.Edit") }}
            </span>
            <span
                class="operationBtn"
                @click="delPrrShowH(row)"
                v-if="checkBtnPermission.userDelete"
            >
              <i class="iconfont zy-common-shanchu"></i>
              {{ $t("common.Delete") }}
            </span>
            <!--                <span class="operationBtn" @click="resetPass(row)"-->
            <!--                      v-if="checkBtnPermission.userResetPwd"><i class="iconfont zy-common-jichushujupeizhi"></i>重置密码</span>-->

            <Dropdown
                trigger="click"
                transfer-class-name="theme-dropdown"
                :transfer="true"
                placement="left-start"
                v-if="checkBtnPermission.userUpdateRole ||
              checkBtnPermission.userUpdate
              "
            >
              <a href="javascript:void(0)">
                <i class="iconfont zy-common-gengduo1"></i>
                {{ $t("common.more") }}
              </a>
              <Dropdown-menu slot="list">
                <Dropdown-item
                    v-if="checkBtnPermission.userResetPwd"
                    @click.native="resetPass(row)"
                >
                  <span class="operationBtn">{{ $t("重置密码") }}</span>
                </Dropdown-item>
                <Dropdown-item
                    v-if="checkBtnPermission.userUpdateRole"
                    @click.native="allotClick(row)"
                >
                  <span class="operationBtn">{{ $t("分配角色") }}</span>
                </Dropdown-item>
                <Dropdown-item v-has="'userUpdateDept'" @click.native="allotbuClick(row)">
                  <span class="operationBtn">{{ $t("分配部门") }}</span>
                </Dropdown-item>
                <Dropdown-item
                    v-if="checkBtnPermission.userUpdate && row.status === 1"
                    @click.native="changeStatus(row)"
                >
                  <span class="operationBtn">{{ $t("common.disable") }}</span>
                </Dropdown-item>
                <Dropdown-item
                    v-if="checkBtnPermission.userUpdate && row.status === 0"
                    @click.native="changeStatus(row)"
                >
                  <span class="operationBtn">{{ $t("启用") }}</span>
                </Dropdown-item>
                <!--                    <Dropdown-item v-has="'userSignature'"  @click.native="setUserSignature(row)">-->
                <!--                      <span class="operationBtn" >{{$t('签名')}}</span>-->
                <!--                    </Dropdown-item>-->
                <!--                    <Dropdown-item v-if="checkBtnPermission.userUpdate"  @click.native="showCertificate(row.id)">
                      <span class="operationBtn">{{$t('证书')}}</span>
                </Dropdown-item>-->
              </Dropdown-menu>
            </Dropdown>
          </template>
        </Table>
      </div>
      <div class="pageWrap mt16">
        <pageLeftTitle :total="total" :selected="delIds.length"/>
        <Page
            :total="total"
            :page-size="pageSize"
            :page-size-opts="$variable.pageSizes"
            :current="pageNum"
            @on-change="changePageNum"
            @on-page-size-change="changePageSize"
            show-sizer
            show-total
        />
      </div>
    </div>
    <Modal
        :mask-closable="false"
        v-model="create"
        :title="addtitle"
        :loading="loading"
        class="modal-content-layout"
        :before-close="createBeforeClose"
        width="800"
    >
      <Row>
        <Col span="10">
          <Tree :data="hierarchyCodedata" show-checkbox :render="renderContent" ref="codeTree"></Tree>
        </Col>
        <Col span="14">
          <Form
              class="formList"
              ref="form"
              :model="formItem"
              :rules="formItemRules"
              label-position="top"
          >
            <FormItem :label="$t('工号')" prop="empno">
              <Input
                  type="text"
                  v-model="formItem.empno"
                  :placeholder="`${$t('common.inputInfo')}`"
                  class="inputBorder"
                  :maxlength="32"
              ></Input>
            </FormItem>
            <FormItem :label="$t('用户名')" prop="userName">
              <Input
                  type="text"
                  v-model="formItem.userName"
                  :placeholder="`${$t('common.inputInfo')}`"
                  class="inputBorder"
                  :maxlength="32"
              ></Input>
            </FormItem>
            <FormItem :label="$t('性别')" prop="sex">
              <Select v-model="formItem.sex" clearable :placeholder="`${$t('common.selectInfo')}`">
                <Option
                    v-for="(item, index) of sexArr"
                    :value="item.id"
                    :key="index"
                    :label="item.name"
                ></Option>
              </Select>
            </FormItem>
            <FormItem :label="$t('姓名')" prop="realName">
              <Input
                  type="text"
                  v-model="formItem.realName"
                  :placeholder="`${$t('common.inputInfo')}`"
                  class="inputBorder"
                  :maxlength="32"
              ></Input>
            </FormItem>
            <!-- <FormItem :label="$t('公司')" prop="companyIdList">
              <Select
                v-model="formItem.companyIdList"
                multiple
                filterable
                clearable
                :placeholder="`${$t('common.selectInfo')}`"
              >
                <Option
                  v-for="(item, index) of companyIdList"
                  :value="item.id"
                  :key="index"
                  :label="item.name"
                >
                </Option>
              </Select>
            </FormItem>-->
            <!--                        <FormItem  label="密码" prop="passWord" v-if="!formItem.id">
                            <Input v-model="formItem.passWord"
                                   type="password" password :placeholder="`${$t('common.inputInfo')}`"/>
            </FormItem>-->
            <FormItem :label="$t('职位')" prop="jobTitle">
              <Input
                  type="text"
                  v-model="formItem.jobTitle"
                  :placeholder="`${$t('common.inputInfo')}`"
                  class="inputBorder"
                  :maxlength="32"
              ></Input>
            </FormItem>
            <FormItem :label="$t('电话')" prop="phone">
              <Input
                  type="text"
                  name="phoneNumber"
                  v-model="formItem.phone"
                  :placeholder="`${$t('common.inputInfo')}`"
                  class="inputBorder"
                  :maxlength="11"
              ></Input>
            </FormItem>
            <FormItem :label="$t('邮箱')" prop="email">
              <Input
                  type="text"
                  v-model="formItem.email"
                  :placeholder="`${$t('common.inputInfo')}`"
                  class="inputBorder"
                  :maxlength="32"
              ></Input>
            </FormItem>

            <FormItem :label="$t('状态')" prop="status" class="textlab" v-if="formItem.id">
              <RadioGroup v-model="formItem.status">
                <Radio label="0">{{ $t("common.disable") }}</Radio>
                <Radio label="1">{{ $t("启用") }}</Radio>
              </RadioGroup>
            </FormItem>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button type="default" @click="createBeforeClose">
          {{
            $t("common.Cancle")
          }}
        </Button>
        <Button type="primary" @click="addOk('form')">
          {{
            $t("maintenance.Confirmed")
          }}
        </Button>
      </div>
    </Modal>

    <!-- 角色分配 -->
    <Modal
        :mask-closable="false"
        v-model="allotShowF"
        :title="$t('分配角色')"
        class="modal-content-layout"
        width="600"
    >
      <template>
        <CheckboxGroup v-model="selectRole">
          <Checkbox
              style="width: 160px; margin: 10px"
              v-for="item in allotGroup"
              :key="item.id"
              :label="item.id"
          >{{ item.name }}
          </Checkbox>
        </CheckboxGroup>
      </template>

      <div slot="footer">
        <Button type="default" @click="allotShowF = false">
          {{
            $t("common.Cancle")
          }}
        </Button>
        <Button type="primary" @click="allotOk">
          {{
            $t("maintenance.Confirmed")
          }}
        </Button>
      </div>
    </Modal>
    <Modal
        :mask-closable="false"
        v-model="delFaultCodeShowF"
        :title="$t('common.Delete')"
        class="modal-title-layout"
        :loading="loading"
    >
      <!--            <Row class="enableContent">-->
      <!--                <Col span="24" class="enableContentInner">-->
      <!--                    <img width="95px" src="~images/event/del.png" alt="">-->
      <!--                </Col>-->
      <!--                <Col span="24" class="enableTips">-->
      <!--                    <span>{{ $t('common.confirmDelete') }}</span>-->
      <!--                </Col>-->
      <!--            </Row>-->
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{ $t("common.confirmDelete") }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="delFaultCodeShowF = false">
          {{
            $t("common.Cancle")
          }}
        </Button>
        <Button type="primary" @click="deleteOk">
          {{
            $t("maintenance.Confirmed")
          }}
        </Button>
      </div>
    </Modal>
    <Modal
        :mask-closable="false"
        v-model="resetPassShowF"
        class="modal-title-layout"
        :title="$t('common.reset')"
    >
      <!--            <Row class="enableContent">-->
      <!--                <Col span="24" class="enableContentInner">-->
      <!--                    <img width="95px" src="~images/person.png" alt="">-->
      <!--                </Col>-->
      <!--                <Col span="24" class="enableTips">-->
      <!--                    <span>请确认是否重置?</span>-->
      <!--                </Col>-->
      <!--            </Row>-->
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{ $t("请确认是否重置?") }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="resetPassShowF = false">
          {{
            $t("common.Cancle")
          }}
        </Button>
        <Button
            type="primary"
            :loading="loading"
            @click="resetPassOk"
        >{{ $t("maintenance.Confirmed") }}
        </Button>
      </div>
    </Modal>
    <Modal
        :mask-closable="false"
        v-model="certificateVisible"
        :title="$t('用户证书')"
        width="60%"
        class="modal-content-layout"
    >
      <Form
          ref="certificateForm"
          :model="formTop"
          label-position="top"
          :rules="validateCertificate"
      >
        <Row :gutter="16">
          <Col :span="8">
            <FormItem :label="$t('证书类型')" prop="certificateType">
              <Select
                  v-model="formTop.certificateType"
                  filterable
                  clearable
                  allow-create
                  @on-create="handleCreate1"
              >
                <Option
                    v-for="item in numberList"
                    :value="item.value"
                    :key="item.value"
                    :label="item.label"
                ></Option>
              </Select>
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem :label="$t('描述')">
              <Input v-model="formTop.certificateDescription"/>
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem :label="$t('上传')">
              <div class="fileWrap">
                <Upload
                    :show-upload-list="false"
                    :before-upload="handleBeforeUpload"
                    type="drag"
                    action
                >
                  <Button icon="ios-cloud-upload-outline">
                    {{
                      $t("上传证书")
                    }}
                  </Button>
                </Upload>
                <div class="fileBox">
                  <span class="file-list" v-for="(item, index) in fileList" :key="index">
                    <span class="item-src">{{ item.fileName }}</span>
                    <Icon
                        class="item-icon"
                        type="ios-trash-outline"
                        style="cursor: pointer"
                        size="20"
                        @click="delFileList($event, index)"
                    ></Icon>
                  </span>
                </div>
              </div>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div style="text-align: right; padding-right: 40px; margin-bottom: 20px">
        <Button type="primary" @click="handleAddCertificate">
          {{
            $t("添加")
          }}
        </Button>
      </div>
      <Table :columns="makeColumns" :data="makeDataSource">
        <template slot-scope="{ row }" slot="attachments">
          <div class="attachBox">
            <div
                v-for="item of row.attachments"
                :key="item.id"
                :style="{ marginRight: row.attachments.length > 1 ? '10px' : '' }"
            >
              <viewer
                  :images="[util.filePathToUrl(item.filePath)]"
                  v-if="item.suffix.includes('png') || item.suffix.includes('jpg')
                "
              >
                <img
                    :src="util.filePathToUrl(item.filePath)"
                    style="width: 40px; height: 40px; overflow: hidden"
                />
              </viewer>
              <Tag color="blue" type="border" v-else>{{ item.fileName }}</Tag>
            </div>
          </div>
        </template>
        <template slot-scope="{ row }" slot="action">
          <span style="color: #1870ff; cursor: pointer" @click="deleteCertificate(row.id)">
            {{
              $t("common.Delete")
            }}
          </span>
        </template>
      </Table>
      <div slot="footer"></div>
    </Modal>

    <Modal :mask-closable="false" v-model="createStatus" :title="$t('分配部门')">
      <Form class="formList">
        <FormItem :label="$t('部门名称')" required>
          <Select
              filterable
              v-model="deptNameId"
              clearable
              :placeholder="`${$t('common.selectInfo')}`"
          >
            <Option
                v-for="item of departmentList"
                :value="item.id"
                :label="item.deptName"
                :key="item.id"
            />
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="cancleInfo">
          {{
            $t("common.Cancle")
          }}
        </Button>
        <Button type="primary" @click="addOkinfo">
          {{
            $t("maintenance.Confirmed")
          }}
        </Button>
      </div>
    </Modal>

    <importExcelModal
        :importExcelStateF="importExcelState"
        v-if="importExcelState"
        @importExcelChange="importExcelChange"
    ></importExcelModal>
    <signature ref="signature" @change="submitSignature"/>
  </div>
</template>

<script>
import {
  Input,
  Checkbox,
  Icon,
  Table,
  Page,
  Select,
  Option,
  Modal,
  Form,
  FormItem
} from "view-design";
import importExcelModal from "@/components/importExcel.vue";
import fileDownload from "js-file-download";
import signature from "../../devBasic/capex/components/signature.vue";
import toggleTableOperation from "@/mixins/toggleTableOperation";

export default {
  name: "faultHandlingMode",
  components: {
    Input,
    Checkbox,
    Icon,
    Table,
    Page,
    Select,
    Option,
    Modal,
    Form,
    FormItem,
    importExcelModal,
    signature
  },
  mixins: [toggleTableOperation],
  data() {
    return {
      tarGetburow: {},
      createStatus: false,
      deptNameId: "",
      selectRole: [], // 角色ID
      certificateVisible: false, // 证书
      userId: null, // 用户id
      formTop: {
        certificateType: "",
        certificateDescription: ""
      },
      validateCertificate: {
        certificateType: [
          {
            required: true,
            message: this.$t("common.selectInfo"),
            trigger: "change"
          }
        ]
      },
      departmentList: [],
      numberList: [],
      fileList: [],
      makeColumns: [
        {
          // title: '证书类型',
          title: `${this.$t("证书类型")}`,
          key: "certificateType",
          align: "center"
        },
        {
          // title: '描述',
          title: `${this.$t("描述")}`,
          key: "certificateDescription",
          align: "center"
        },
        {
          // title: '附件',
          title: `${this.$t("附件")}`,
          key: "attachments",
          align: "center",
          minWidth: 400,
          slot: "attachments"
        },
        {
          title: `${this.$t("common.operation")}`,
          slot: "action",
          align: "center"
        }
      ],
      makeDataSource: [],
      importExcelState: false,
      //   companyIdList: [],
      allotGroup: [],
      resetPassShowF: false,
      sexArr: [
        {id: 1, name: this.$t("男")},
        {id: 2, name: this.$t("女")}
      ],
      searchParams: {
        status: 2,
        certificate: -1
      },
      data2: [
        {
          title: "parent 1",
          expand: true,
          children: [
            {
              title: "parent 1-1",
              expand: true,
              children: [
                {
                  title: "leaf 1-1-1"
                },
                {
                  title: "leaf 1-1-2"
                }
              ]
            },
            {
              title: "parent 1-2",
              expand: true,
              children: [
                {
                  title: "leaf 1-2-1"
                },
                {
                  title: "leaf 1-2-1"
                }
              ]
            }
          ]
        }
      ],
      hierarchyCodedata: [],
      formItem: {
        empno: "",
        userName: "",
        sex: "",
        realName: "",
        // companyIdList: "",
        phone: "",
        passWord: "",
        jobTitle: "",
        email: "",
        department: "",
        status: ""
      },
      formItemRules: {
        empno: [
          {
            required: true,
            message: this.$t("common.inputInfo"),
            trigger: "blur"
          }
        ],
        userName: [
          {
            required: true,
            message: this.$t("common.inputInfo"),
            trigger: "blur"
          }
        ],
        realName: [
          {
            required: true,
            message: this.$t("common.inputInfo"),
            trigger: "blur"
          }
        ],
        companyIdList: [
          {
            required: true,
            message: this.$t("common.selectInfo"),
            trigger: "change",
            type: "array"
          }
        ],
        passWord: [
          {
            required: true,
            message: this.$t("common.inputInfo"),
            trigger: "blur"
          }
        ],
        phone: [
          {
            required: true,
            message: this.$t("common.inputInfo"),
            trigger: "blur"
          }
        ],
        email: [
          {
            required: true,
            message: this.$t("common.inputInfo"),
            trigger: "blur"
          }
        ]
      },
      addtitle: "",
      allCheck: false,
      loading: false,
      create: false,
      update: false,
      selectionId: [],
      selectionIdShow: false,
      materialTypeId: "",
      pageNum: 1,
      pageSize: 10,
      total: 0,
      columns: [
        {
          key: "selection",
          type: "selection",
          width: 60,
          align: "center"
        },
        // {
        //   title: `${this.$t("公司")}`,
        //   key: "companyName",
        //   align: "center",
        //   width: 150,
        //   resizable: true,tooltip: true,
        //   render: (h, params) => {
        //     let texts = params.row.companyName;
        //     if (params.row.companyName != null) {
        //       if (params.row.companyName.length > 10) {
        //         texts = params.row.companyName.substring(0, 10) + "...";
        //       } else {
        //         texts = params.row.companyName;
        //       }
        //     }
        //     return h(
        //       "Tooltip",
        //       {
        //         props: {
        //           placement: "right-end",
        //         },
        //       },
        //       [
        //         texts,
        //         h(
        //           "span",
        //           {
        //             slot: "content",
        //             style: {
        //               whiteSpace: "normal",
        //               wordBreak: "break-all",
        //             },
        //           },
        //           params.row.companyName
        //         ),
        //       ]
        //     );
        //   },
        // },
        {
          // title: '用户名',
          title: `${this.$t("用户名")}`,
          key: "username",
          width: 150,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          // title: '姓名',
          title: `${this.$t("姓名")}`,
          key: "realname",
          width: 150,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          // title: '工号',
          title: `${this.$t("工号")}`,
          key: "empno",
          width: 150,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          // title: '状态',
          title: `${this.$t("状态")}`,
          key: "status",
          align: "center",
          width: 150,
          resizable: true,
          tooltip: true,
          render: (h, params) => {
            if (params.row.status == 1) {
              return h("div", [h("span", {style: {}}, this.$t("启用"))]);
            }
            if (params.row.status == 0) {
              return h("div", [
                h("span", {style: {}}, this.$t("common.disable"))
              ]);
            }
          }
        },
        {
          // title: '职位',
          title: `${this.$t("职位")}`,
          key: "jobTitle",
          width: 150,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          // title: '部门',
          title: `${this.$t("部门")}`,
          key: "deptName",
          width: 150,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: `${this.$t("角色")}`,
          key: "roleName",
          width: 150,
          tooltip: true,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          // title: '邮箱',
          title: `${this.$t("邮箱")}`,
          key: "email",
          width: 150,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          // title: '性别',
          title: `${this.$t("性别")}`,
          key: "sex",
          width: 150,
          align: "center",
          resizable: true,
          tooltip: true,
          render: (h, params) => {
            if (params.row.sex == 1) {
              return h("div", [h("span", {style: {}}, this.$t("男"))]);
            }
            if (params.row.sex == 2) {
              return h("div", [h("span", {style: {}}, this.$t("女"))]);
            }
          }
        },
        {
          // title: '电话',
          title: `${this.$t("电话")}`,
          key: "phone",
          width: 150,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          // title: '创建时间',
          title: `${this.$t("创建时间")}`,
          key: "createTime",
          width: 180,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          // title: '更新时间',
          title: `${this.$t("更新时间")}`,
          key: "updateTime",
          width: 180,
          align: "center",
          resizable: true,
          tooltip: true
        },
        {
          title: `${this.$t("common.operation")}`,
          slot: "action",
          fixed: "right",
          width: 260,
          align: "center"
        }
      ],
      dataArr: [],
      materialTypeArr: [],
      materialTypeArr1: [],
      importFaultCodeShowF: false, //是否显示批量导入弹窗
      delFaultCodeShowF: false, //是否显示删除弹窗
      pageSizeOption: [10, 20, 30, 40],
      delIds: [],
      selection: [],
      userInfoArr: [],
      userNoArr: [],
      statusArr: [
        {id: 2, name: this.$t("全部")},
        {id: 1, name: this.$t("启用")},
        {id: 0, name: this.$t("common.disable")}
      ],
      resetPassID: "",
      allotShowF: false,
      allotUserId: "",
      checkBtnPermission: {},
      timeID: null,
      currentItem: {}
    };
  },
  created() {
    this.getTableColumnsWidth(this.columns);
  },
  mounted() {
    // this.getMaterialType();
    this.getDept();
    this.searchList();
    this.getCompanyIdList();
    let itemList = JSON.parse(window.localStorage.getItem("USER_URI"));
    for (let item of itemList) {
      if (item.code == "userFindUserList") {
        this.checkBtnPermission.userFindUserList = true;
      }
      if (item.code == "userInsert") {
        this.checkBtnPermission.userInsert = true;
      }
      if (item.code == "userUpdate") {
        this.checkBtnPermission.userUpdate = true;
      }
      if (item.code == "userDelete") {
        this.checkBtnPermission.userDelete = true;
      }
      if (item.code == "userUpdateRole") {
        this.checkBtnPermission.userUpdateRole = true;
      }
      if (item.code == "userResetPwd") {
        this.checkBtnPermission.userResetPwd = true;
      }
      if (item.code == "userImport") {
        this.checkBtnPermission.userImport = true;
      }
      if (item.code == "userTemplate") {
        this.checkBtnPermission.userTemplate = true;
      }
    }
  },
  methods: {
    submitSignature({filepath}) {
      this.axios({
        method: "post",
        url: "/basic/user/updateSign",
        data: {signPath: filepath, id: this.currentItem.id}
      })
          .then(res => {
            if (res.code == 200) {
              this.$refs.signature.hideModal();
              this.searchList();
            } else {
              this.$Message.warning({
                content: res.msg,
                duration: 6,
                closable: true
              });
            }
          })
          .catch(() => {
          });
    },
    setUserSignature(item) {
      this.currentItem = item;
      this.$refs.signature.showModal(item);
    },
    remoteMethod(query) {
      if (query !== "") {
        if (this.timeID) {
          clearTimeout(this.timeID);
        }
        this.timeID = setTimeout(() => {
          this.getDept(query);
        }, 500);
      } else {
        this.departmentList = [];
      }
    },
    //查询部门
    getDept(value) {
      let data = {
        deptName: value,
        pageNo: 1,
        pageSize: 1000
      };
      this.axios({
        method: "post",
        url: "/basic/dept/list",
        data
      }).then(res => {
        if (res.code === 200) {
          this.departmentList = res.data.list;
        }
      });
    },
    showCertificate(id) {
      this.certificateVisible = true;
      this.userId = id;
      this.getNumberList();
      this.getTableList();
      this.fileList = [];
      this.$refs.certificateForm.resetFields();
      this.formTop.certificateDescription = "";
    },
    getNumberList() {
      this.axios({
        method: "get",
        url: "/dms/certificate/types",
        params: {
          userId: this.userId,
          certificateType: ""
        }
      }).then(res => {
        if (res.code === 200) {
          this.numberList = res.data.map(v => ({
            label: v.certificateType,
            value: v.certificateType
          }));
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    getTableList() {
      this.axios({
        method: "get",
        url: "/dms/certificate/list",
        params: {
          userId: this.userId
        }
      }).then(res => {
        if (res.code === 200) {
          this.makeDataSource = res.data;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    handleCreate1(val) {
      this.numberList.push({
        value: val,
        label: val
      });
    },
    handleAddCertificate() {
      this.$refs.certificateForm.validate(valid => {
        if (valid) {
          this.axios({
            method: "post",
            url: "/dms/certificate/add",
            data: {
              certificateType: this.formTop.certificateType,
              certificateDescription: this.formTop.certificateDescription,
              certificateOwner: this.userId,
              attachments: this.fileList.map(v => ({
                ...v,
                fileDescription: this.formTop.certificateDescription
              }))
            }
          }).then(res => {
            if (res.code === 200) {
              this.$Message.success(res.msg);
              this.getTableList();
              this.getNumberList();
              this.fileList = [];
              this.$refs.certificateForm.resetFields();
              this.formTop.certificateDescription = "";
            } else {
              this.$Message.error(res.msg);
            }
          });
        }
      });
    },
    batchChangeStatus(status) {
      if (this.delIds.length === 0) {
        this.$Message.warning({
          content: this.$t("请选择要操作的用户"),
          duration: 6,
          closable: true
        });
        return;
      }

      this.axios({
        method: "post",
        url: "/basic/user/updateBatchStatus",
        params: {
          status: status
        },
        data: this.delIds
      }).then(res => {
        if (res.code === 200) {
          this.$Message.success(res.msg);
          this.searchList();
          this.delIds = []; // Clear selection
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    deleteCertificate(id) {
      this.axios({
        method: "post",
        url: "/dms/certificate/delete",
        data: [id]
      }).then(res => {
        if (res.code === 200) {
          this.$Message.success(res.msg);
          this.getTableList();
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    //文件上传
    handleBeforeUpload(file) {
      let formData = new FormData();
      formData.append("dir", "device");
      formData.append("file", file);
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      this.axios({
        method: "post",
        url: "/fileServer/upload",
        data: formData,
        config
      }).then(res => {
        if (res.code === 200) {
          this.fileList.push({
            fileName: res.data.fileName,
            filePath: res.data.filepath,
            fileUrl: res.data.fileUrl,
            suffix: res.data.suffix
          });
        }
      });
      return false;
    },
    //文件删除
    delFileList(e, i) {
      e.stopPropagation();
      this.fileList.splice(i, 1);
    },
    checkPhone(value) {
      let regPone = null;
      let mobile = /^(1[3456789]\d{9})$/;
      let tel = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/;
      if (value !== null && value.charAt(0) === "0") {
        regPone = tel;
      } else if (value !== null && value.charAt(0) !== "0") {
        regPone = mobile;
      }
      if (regPone === null) {
        return false;
      } else if (!regPone.test(value)) {
        return false;
      } else {
        return true;
      }
    },
    /*导入*/
    importExcelShow() {
      this.importExcelState = true;
    },
    //导出
    exportTemplate() {
      const filName = this.$t("用户导入模板");
      this.axios({
        method: "get",
        url: "/basic/user/template",
        responseType: "blob",
        params: {}
      }).then(res => {
        fileDownload(res, filName + ".xlsx");
      });
    },
    importExcelChange(val) {
      this.importExcelState = false;
      if (val === "success") {
        this.$Message.success("导入成功!");
        this.changeNum();
      }
    },
    getCompanyIdList() {
      this.axios({
        method: "get",
        url: "/basic/company/search",
        params: {}
      }).then(res => {
        if (res.code === 200) {
          this.companyIdList = res.data;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    renderContent(h, {data}) {
      return h(
          "span",
          {
            style: {
              display: "inline-block",
              width: "100%",
              fontSize: "15px"
            }
          },
          [
            h("span", [h("span", data.name)]),
            h("span", {
              style: {
                display: "inline-block",
                float: "right",
                marginRight: "32px"
              }
            })
          ]
      );
    },
    getList(row) {
      if (row) {
        this.axios({
          method: "get",
          url: "/basic/user/userInfoById",
          params: {
            id: row
          }
        }).then(res => {
          if (res.code === 200) {
            this.hierarchyCodedata = res.data.orgList || [];
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true
            });
          }
          this.create = true;
        });
      } else {
        this.axios({
          method: "get",
          url: "/basic/organization/findList",
          params: {}
        }).then(res => {
          if (res.code === 200) {
            this.hierarchyCodedata = res.data;
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true
            });
          }
        });
      }
    },
    resetPass(row) {
      this.resetPassShowF = true;
      this.resetPassID = row.id;
    },
    resetPassOk() {
      this.loading = true;
      this.axios({
        method: "get",
        url: "/basic/user/resetPwd",
        params: {
          userId: this.resetPassID
        }
      }).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$Message.success(res.msg);
          this.resetPassShowF = false;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    allotOk() {
      if (this.selectRole.length < 1) {
        this.$Message.error(this.$t("请分配角色"));
        return;
      }
      // let role = this.allotGroup.find((item) => item.name === this.selectRole);

      this.axios({
        method: "post",
        url: "/basic/user/updateRole",
        data: {
          userId: this.allotUserId,
          roleIds: this.selectRole
        }
      }).then(res => {
        if (res.code === 200) {
          this.$Message.success(res.msg);
          this.searchList();
          this.allotShowF = false;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    cancleInfo() {
      this.createStatus = false;
      this.deptNameId = null;
      //this.departmentList = []
    },
    addOkinfo() {
      if (!this.deptNameId) {
        this.$Message.warning({
          content: this.$t("请选择部门!"),
          duration: 6,
          closable: true
        });
        return;
      }
      this.axios({
        method: "post",
        url: "/basic/user/updateDept",
        params: {
          deptId: this.deptNameId,
          userId: this.tarGetburow.id
        }
      }).then(res => {
        if (res.code === 200) {
          this.$Message.success({
            content: res.msg,
            duration: 6,
            closable: true
          });
          this.searchList();
          this.cancleInfo();
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    allotbuClick(row) {
      this.deptNameId = row.deptId;
      this.createStatus = true;
      this.tarGetburow = row;
    },
    allotClick(row) {
      this.selectRole = [];
      this.allotUserId = row.id;
      this.allotShowF = true;
      this.axios({
        method: "get",
        url: "/basic/user/find",
        params: {
          userId: row.id
        }
      }).then(res => {
        if (res.code === 200) {
          this.allotGroup = res.data;
          // let currentRole = this.allotGroup.find(item => item.checked);
          // if(currentRole){
          this.allotGroup.forEach(item => {
            if (item.checked) {
              this.selectRole.push(item.id);
            }
          });
          // }
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    getHcode() {
      // this.searchParams.orgCode = tree
    },
    //延时查询
    timeOutgetUserNo(query) {
      clearTimeout(this.timeout);
      let isSearchF = false;
      this.timeout = setTimeout(() => {
        if (query != "") {
          for (let item of this.userNoArr) {
            if (
                item.empno == query ||
                item.empno + "-" + item.realname == query ||
                item.realname == query
            ) {
              isSearchF = true;
            }
          }
          if (isSearchF == false) {
            this.getUserNo(query);
          }
        }
      }, 500);
    },
    getUserNo(query) {
      this.axios({
        method: "get",
        url: "/basic/user/searchUser",
        params: {
          key: query
        }
      }).then(res => {
        if (res.code === 200) {
          this.userNoArr = res.data;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    //延时查询
    timeOutgetUserInfo(query) {
      clearTimeout(this.timeout);
      let isSearchF = false;
      this.timeout = setTimeout(() => {
        if (query != "") {
          for (let item of this.userInfoArr) {
            if (
                item.realname == query ||
                item.empno == query ||
                item.empno + "-" + item.realname == query
            ) {
              isSearchF = true;
            }
          }
          if (isSearchF == false) {
            this.getUserInfo(query);
          }
        }
      }, 500);
    },
    getUserInfo(query) {
      this.axios({
        method: "get",
        url: "/basic/user/searchUser",
        params: {
          realname: query
        }
      }).then(res => {
        if (res.code === 200) {
          this.userInfoArr = res.data;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    reset() {
      this.searchParams = {
        status: 2,
        certificate: -1
      };
      this.changeNum();
    },
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    searchList() {
      //查询列表
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        realName: this.searchParams.realName,
        empno: this.searchParams.empno,
        orgCode: this.searchParams.orgCode,
        certificate: this.searchParams.certificate,
        deptId: this.searchParams.deptId,
        empNoOrName: this.searchParams.empNoOrName,
      };
      if (this.searchParams.status === 2) {
        params.status = "";
      } else {
        params.status = this.searchParams.status;
      }
      this.axios({
        method: "get",
        url: "/basic/user/findUserList",
        params: params
      }).then(res => {
        if (res.code === 200) {
          this.dataArr = res.data.list;
          this.total = res.data.total;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    changeStatus(row, status) {
      let params = {
        userId: row.id,
        status: row.status
      };

      this.axios({
        method: "post",
        url: "/basic/user/updateStatus",
        params: params
      }).then(res => {
        if (res.code === 200) {
          this.changeNum();
          this.$Message.success(res.msg);
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    },
    createfaultCodeShowH(row) {
      //点击增加或编辑

      this.$nextTick(() => {
        this.create = true;
        // this.$refs['formItem'].resetFields();
        if (row.id) {
          this.addtitle = `${this.$t("common.Edit")}`;
          this.formItem.id = row.id;
          this.formItem.userName = row.username;
          this.formItem.status = row.status.toString();
          this.formItem.sex = row.sex;
          this.formItem.realName = row.realname;
          this.formItem.phone = row.phone;
          this.formItem.jobTitle = row.jobTitle;
          this.formItem.empno = row.empno;
          this.formItem.email = row.email;
          this.formItem.department = row.department;
          if (row.companyId) {
            this.formItem.companyIdList = row.companyId.split(",").map(Number);
          }
          this.getList(row.id);
        } else {
          this.formItem = {
            ...this.formItem,
            phone: "",
            passWord: "123456"
          };
          this.addtitle = `${this.$t("common.New")}`;
          this.getList();
        }
      });
    },
    delFaultCodeShowClick() {
      //点击批量删除
      if (!this.allCheck) {
        this.$Message.warning(this.$t("common.selectInfo"));
        return;
      }
      this.delFaultCodeShowF = true;
    },
    onSelectChange(selection) {
      let myArray = [];
      selection.map(item => {
        myArray.push(item.id);
      });
      this.delIds = myArray;
      if (selection.length > 0) {
        this.allCheck = true;
      } else {
        this.allCheck = false;
      }
    },
    cancle() {
      this.formItem = {};
      this.create = false;
    },
    createBeforeClose() {
      this.formItem = {};
      this.$refs["form"].resetFields();
      this.create = false;
    },
    addOk(name) {
      this.$refs[name].validate(valid => {
        if (!valid) {
          return;
        } else {
          const flag = this.checkPhone(this.formItem.phone);
          if (!flag) {
            this.$Message.warning({
              content: this.$t("请输入正确电话格式"),
              duration: 6,
              closable: true
            });
            return;
          }

          let orgIdList = this.$refs.codeTree.getCheckedNodes();
          this.formItem.orgIdList = [];
          if (orgIdList.length > 0) {
            for (let item of orgIdList) {
              this.formItem.orgIdList.push(item.id);
            }
          } else {
            this.$Message.warning({
              content: this.$t("请选择层级"),
              duration: 6,
              closable: true
            });
            return false;
          }
          this.loading = true;
          if (this.formItem.id) {
            this.axios({
              method: "post",
              url: "/basic/user/update",
              data: this.formItem
            }).then(res => {
              this.loading = false;
              if (res.code === 200) {
                // this.changeNum();
                this.searchList();
                this.$Message.success(res.msg);
                this.cancle("formCustomInfo");
              } else {
                this.$Message.warning({
                  content: res.msg,
                  duration: 6,
                  closable: true
                });
              }
            });
          } else {
            this.axios({
              method: "post",
              url: "/basic/user/insert",
              data: this.formItem
            }).then(res => {
              this.loading = false;
              if (res.code === 200) {
                this.changeNum();
                this.$Message.success(res.msg);
                this.cancle("formCustomInfo");
              } else {
                this.$Message.warning({
                  content: res.msg,
                  duration: 6,
                  closable: true
                });
              }
            });
          }
        }
      });
    },
    delPrrShowH(row) {
      //点击展示提示删除弹窗
      this.delFaultCodeShowF = true;
      this.delIds = [];
      this.delIds.push(row.id);
    },
    deleteOk() {
      this.loading = true;
      this.axios({
        method: "post",
        url: "/basic/user/delete",
        data: {
          ids: this.delIds
        }
      }).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.changeNum();
          this.$Message.success(res.msg);
          this.delFaultCodeShowF = false;
          this.allCheck = false;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true
          });
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.faultHandlingMode {
  .formList {
    padding: 30px;

    .btn {
      margin-top: 20px;
      text-align: center;
      width: 100%;
      height: 40px;
    }

    .inputBorder {
      border: 1px solid #dcdee2;
      border-radius: 4px;
    }
  }
}

.attachBox {
  display: flex;
  align-items: center;
  justify-content: center;
}

.fileWrap {
  display: flex;
  //margin-top: 30px;

  .fileBox {
    flex: 1;
    display: flex;
    overflow-y: scroll;
    flex-direction: column;
    height: 32px;

    &::-webkit-scrollbar {
      width: 4px;
    }
  }

  .file-list {
    height: 32px;
    line-height: 32px;
    padding-left: 20px;
  }
}

/deep/ .ivu-upload-drag:hover {
  border: none;
}

/deep/ .ivu-upload-drag {
  border: none;
}

/deep/ .ivu-icon {
  font-size: 20px;
}
</style>

<style lang="scss"></style>
